/**
 * 主功能页面，用于加载首页，包括左边树和右边主要内容
 * author:zhushy
 * date:2016年8月29日12:43:42
 */
var keyIndustryMaintance = {
	/**
	 * 初始化左边树结构
	 */
	initLeftTree:function(){	
		
		treenode = {
			 productNameLabel:"一级行业名称：",
			 level:0,
			 name: "",
		     pId : "",
		     order_num : "",
		     id : "",
		     productId:"",
		     productname:""
		}
				
		//调用后台接口，取得树形结构的列表
		//转圈
		common.showLoading();
		var url = "/PCIndustryChart/pc/ztreeQuery";
		common.interfaceAjaxFunction(url,"",this.showLeftPartTreeSuccess);
		$("#kmProduct").hide();
		 
		//-->
	},
	//获取树节点 存储在全局变量treenode中
	setTreeNode:function(treeNode){
		var productNameLabel = "一级商品名称：";
		switch (treeNode.level) {
		 	case 0:
		   		productNameLabel = "一级商品名称：";
				break;
			case 1:
				productNameLabel= "二级商品名称：";
				break;
			case 2:
				productNameLabel= "三级商品名称：";
				break;
			case 3:
				productNameLabel= "商品名称：";
				break;
			case 4:
				productNameLabel= "规格名称：";
				break;
			case 5:
				productNameLabel = "名称：";
				break;
			default:
				productNameLabel = "一级行业名称：";
				break;
	   }
	   treenode.productNameLabel=productNameLabel;
	   treenode.level = treeNode.level;
	   treenode.name = treeNode.name;
	   treenode.pId = treeNode.pId;
	   treenode.order_num = treeNode.order_num;
	   treenode.id = treeNode.id;    
	},
	//显示树节点
	showTreeNode:function(treeNode){
		if (!treeNode.productNameLabel || treeNode.productNameLabel.length ==0) {
			var productNameLabel = "行业名称：";
			switch (treeNode.level) {
			   	case 0:
					productNameLabel = "行业名称：";
					break;
				case 1:
					productNameLabel = "工序名称：";
					break;
				case 2:
					productNameLabel = "设备名称：";
					break;
				case 3:
					productNameLabel = "用油点名称：";
					break;
				default:
					productNameLabel = "行业名称：";
					break;
		   }
		   treeNode.productNameLabel=productNameLabel;
		}
		if(treeNode.level == 5){
			$("#newlyAdded").hide();
		   		$("#kmProduct").show();
		   		var param = {
		   			"pk_industry_chart":treeNode.id,
		   			"type":"2",
		   			"name":""
		   		};
				//调用ajax
				var ajaxUrl = "/pcBdproduct/queryProduct";
				//转圈提示
    			common.showLoading();
				common.interfaceAjaxFunction(ajaxUrl,param,function(res){
					common.hideLoading();
					if (res.status== 0) {
						var productId = "";
						var productName ="";
						for (var i=0; i < res.data.length; i++) {
						 productId += res.data[i].pk_product+",";
						 if(res.data[i].product_name){
						 	productName +=res.data[i].product_name+",";
						 } 
						};
						productName = productName.substring(0,productName.length-1);
						productId = productId.substring(0,productId.length-1);
						treenode.productId=productId;
						treenode.productName=productName;
						$("#kmProductInput").val(productName);
						$("#kmProductInput").text(productId);
					}else{
						
					}
					
				});
		   }else{
		   	   $("#newlyAdded").show();
		   		$("#kmProduct").hide();
		   }
		   $("#productNameLabel").text(treeNode.productNameLabel);
		   // 名字 cate_name
		   $("#productNameInput").val(treeNode.name);
		   // 父节点id fw_parent
		   $("#productNameInput").text(treeNode.pId);
		   // 排序 order_num
		   $("#orderNumInput").val(treeNode.order_num);
		   //  节点id pk_industry_chart
		   $("#orderNumInput").text(treeNode.id);
		   
	},
	showProduct:function(){
		var str =window.sessionStorage.products;
		var products =JSON.parse(str);
		$("#kmProductInput").val(products.productName);
		$("#kmProductInput").text(products.productId);

	},
	/**
	 * 调用取得树的结构,然后进行数据的渲染
	 */
	showLeftPartTreeSuccess:function(json){
		//成功时候
    	if(json.status == "0"){
    		if(json.data.length > 0){
	    		//加载设置后的主页面
    			keyIndustryMaintance.showLeftPartTree(json.data);
    		}else{
    			//加载设置页面
    			common.show_error("当前无行业树结构数据，请联系管理员维护");
    		}
    	}else{
    		//给出信息提示
    		common.show_error(json.message);
    	}
    	//转圈提示去除
    	common.hideLoading();
	},
	/**
	 * 显示showLeftPartTree函数，渲染显示数据
	 */
	showLeftPartTree:function(jsonData){
		var setting = {
				data: {
					key: {
						title: "title"
					},
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: this.beforeClick,
					onClick: this.onClick,
					beforeRemove: this.beforeRemove,
					beforeRename: this.beforeRename,
					onRemove: this.onRemove
				}
			};
		//公共用的树结构
		var zNodes =[];
		//循环得到的data数据，然后进行push到zNodes中去
		for(var i=0;i<jsonData.length;i++){
			var jsonDataRow = jsonData[i];
			var jsonStruct = {
				id:	jsonDataRow.pk_industry_chart,
				pId:jsonDataRow.fw_parent,
				name:jsonDataRow.cate_name,
				order_num:jsonDataRow.order_num,
				title:jsonDataRow.cate_name,
				seal_mark:jsonDataRow.seal_mark
			};
			//压入到树结构中去
			zNodes.push(jsonStruct);
		}
		$.fn.zTree.init($("#leftTreeIndustry"), setting, zNodes);
		$("#hideNodesBtn").bind("click", {type:"rename"}, this.hideTreeNodes);
		$("#showNodesBtn").bind("click", {type:"icon"}, this.showTreeNodes);
	},
	/**
	 * 设置树的title
	 */
	setTreeTitle:function(node) {
		var zTree = $.fn.zTree.getZTreeObj("leftTree");
		var nodes = node ? [node]:zTree.transformToArray(zTree.getNodes());
		for (var i=0, l=nodes.length; i<l; i++) {
			var n = nodes[i];
			n.title = "[" + n.id + "] isFirstNode = " + n.isFirstNode + ", isLastNode = " + n.isLastNode;
			zTree.updateNode(n);
		}
	},
	beforeRemove:function (treeId, treeNode) {
		
	},
	onRemove:function(e, treeId, treeNode) {
		
	},
	beforeRename:function (treeId, treeNode, newName) {
		if (newName.length == 0) {
			alert("节点名称不能为空.");
			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
			setTimeout(function(){zTree.editName(treeNode)}, 10);
			return false;
		}
		return true;
	},
	//树节点 点击方法回调
	beforeClick:function(treeId, treeNode, clickFlag) {
		if(clickFlag ==1){
			//console.log(treeNode);
		}
		
	},
	//树节点 点击方法 回调
	onClick:function(event, treeId, treeNode, clickFlag) {
		if(clickFlag ==1){
			window.sessionStorage.removeItem("key_productId");
			$("#keyIndustryMaintanceRight").show();
			keyIndustryMaintance.setTreeNode(treeNode);
			keyIndustryMaintance.showTreeNode(treenode);
			
		}
	},		
	/**
	 * 显示树的节点
	 */
	showTreeNodes:function(){
		var zTree = $.fn.zTree.getZTreeObj("leftTree"),
		nodes = zTree.getNodesByParam("isHidden", true);
		zTree.showNodes(nodes);
		mainParam.setTreeTitle();
		mainParam.countTree();
	},
	/**
	 * 隐藏输的节点
	 */
	hideTreeNodes:function() {
		var zTree = $.fn.zTree.getZTreeObj("leftTree"),
		nodes = zTree.getSelectedNodes();
		if (nodes.length == 0) {
			alert("请至少选择一个节点");
			return;
		}
		zTree.hideNodes(nodes);
		mainParam.setTreeTitle();
		mainParam.countTree();
	},
	/**
	 * 查询数的数目
	 */
    countTree:function() {
		var zTree = $.fn.zTree.getZTreeObj("leftTree"),
		hiddenCount = zTree.getNodesByParam("isHidden", true).length;
		$("#hiddenCount").text(hiddenCount);
	},
	/**
	 * 初始化窗口高度
	 */
	initPageHeight:function(){
		//整体高度
		var winHeight = $(window).height();
		//top高度
		var winTopHeight = $(".shell-top-box").height();
		// //左边的高度为
		// $("#leftTree").height(winHeight-winTopHeight-$("#addIndustry").height()-30);
		var height =winHeight-winTopHeight-$("#addIndustry").height()-30;
		$(".leftHeight").css("height",height);
		$("#kmProduct").hide();
		
		
	},
	deleteSucess:function(res){
		common.hideLoading();
		if (res.status==0) {
			treenode = {
				 productNameLabel:"",
				 level:"",
				 name: "",
			     pId : "",
			     order_num : "",
			     id : ""
		    };
			keyIndustryMaintance.showTreeNode(treenode);
			
			var zTree = $.fn.zTree.getZTreeObj("leftTreeIndustry"),
			nodes = zTree.getSelectedNodes(),
			treeNode = nodes[0];
			if (nodes.length == 0) {
				alert("请先选择一个节点");
				return;
			}
			var callbackFlag = $("#callbackTrigger").attr("checked");
			zTree.removeNode(treeNode, callbackFlag);
			layer.msg("删除成功");
		}else{
			layer.msg(res.message);
		}
		
	},
	insertSucess:function(res){
		common.hideLoading();
		if (res.status==0) {
			var zTree = $.fn.zTree.getZTreeObj("leftTreeIndustry");
			nodes = zTree.getSelectedNodes();
			treeNode = nodes[0];
			zTree.addNodes(treeNode, {id:res.data.pk_industry_chart, pId:res.data.fw_parent, name:res.data.cate_name,order_num:res.data.order_num,});
		    keyIndustryMaintance.showTreeNode(treenode);
            $("#cancleButton").hide();
            layer.msg("新增成功");
		}else{
			layer.msg(res.message);
		}
		
	},
	productInsertSucess:function(res){
		common.hideLoading();
		if (res.status==0){
			
		}else{
			layer.msg("用油点关联产品失败，请重试");
		}
		// layer.msg(res.message);
	},
	updateSucess:function(res){
		common.hideLoading();
		if (res.status==0) {
			
			var zTree = $.fn.zTree.getZTreeObj("leftTreeIndustry");
			var nodes = zTree.getSelectedNodes();
			nodes[0].name =  $("#productNameInput").val();
			nodes[0].order_num = $("#orderNumInput").val();
			zTree.updateNode(nodes[0]);
			layer.msg("修改成功");
			
		}else{
			layer.msg(res.message);
		}
		
	},
	bindEvent :function(){
		var _this= this;
		window.sessionStorage.removeItem("key_productId");
		// //点击标题 新增行业
		// $("#addIndustry").unbind().on("click", function () {
			// var newtreeNode = {
						 // productNameLabel:"行业名称：",
						 // level:0,
						 // name: "",
					     // order_num : "",
					     // id : ""
			// }
			// keyIndustryMaintance.showTreeNode(newtreeNode);
            // // $("#cancleButton").show();
		// });
		//新增按钮 点击
		$("#newlyAdded").unbind().on("click", function () {
			if(treenode.level<5){
				var newtreeNode = {
					 productNameLabel:"行业名称：",
					 level:0,
					 name: "",
				     order_num : "",
				     id : "",
				     pId :""
				 }
				 pId = $("#productNameInput").text();
				 id = $("#orderNumInput").text();
				 if (id.length == 0 &&pId.length==0 ) {
				 	
				 }else{
				 	newtreeNode = {
						 productNameLabel:"",
						 level:treenode.level+1,
						 name: "",
					     pId : treenode.id,
					     order_num : "",
					     id : ""
					}
				 }
				window.sessionStorage.newtreeNode = JSON.stringify(newtreeNode);
				var title = "";
				switch (newtreeNode.level) {
				   	case 0:
						title = "新增一级行业";
						break;
					case 1:
						title= "新增二级行业";
						break;
					case 2:
						title= "新增三级行业";
						break;
					case 3:
						title= "新增工序";
						break;
					case 4:
						title= "新增设备";
						break;
					case 5:
						title = "新增用油点";
						break;
					default:
						title = "新增一级行业";
						break;
			   }
				layer.ready(function () {
	                //增加编辑
	                layer.open({
				    type: 2,
				    title: title,
				    fix: false,
				    shadeClose: true,
				    maxmin: false,
				    area: ['1000px', '600px'],
				    content:'html/keyIndustyMaintanceAdd.html',
				  });
	            });
			}else{
				layer.msg("最多支持四级");
			}
			
			
        });
        //删除按钮 点击
		$("#removeItem").unbind().on("click", function () {
			
			   var pk_industry_chart= $("#orderNumInput").text();
			   var Aname = $("#productNameInput").val();
			   var label =  $("#productNameLabel").text();
               if (pk_industry_chart) {
               		label = label.substring(0,2);
	               	layer.confirm("您确认要删除"+label+":"+Aname+"吗？", {area: ['400px', '200px'],title:'删除'}, function(){
	               		var param = {
							"pk_industry_chart":pk_industry_chart
				    	};
						//调用ajax
						var ajaxUrl = "/PCIndustryChart/delete";
						//转圈提示
		    			common.showLoading();
						common.interfaceAjaxFunction(ajaxUrl,param,_this.deleteSucess);
					}, function(){
			 
					});
               }else{
               	   layer.msg("请先选择节点");
               }
			
          
        });
        //选择按钮
        $("#productchoose-btn").unbind().on("click", function () {
        	var ids = $("#kmProductInput").text();
        	//传入 对应产品的id
	        window.sessionStorage.productIds =$("#kmProductInput").text() ;
	        window.sessionStorage.productNames =$("#kmProductInput").val();
        	window.sessionStorage.removeItem('layerIndex');
            //页面一打开就执行，放入ready是为了layer所需配件（css、扩展模块）加载完毕
            layer.ready(function () {
                //增加编辑
               layer.open({
			    type: 2,
			    //skin: 'layui-layer-lan',
			    title: '选择壳牌产品',
			    fix: false,
			    shadeClose: true,
			    maxmin: false,
			    area: ['1000px', '600px'],
			    // content: 'html/keyIndustryMaintanceChoose.html',
			    content:'html/keyIndustryMaintanceChoose.html',
			  });
            });
        });
        //保存按钮 点击
		$("#saveSetting").unbind().on("click", function () {
		   pId = $("#productNameInput").text();
		   id = $("#orderNumInput").text();
		   
		   
			if (id.length == 0 &&pId.length==0 ) {
				var fw_parent= pId;
               		var param = {
					  "fw_parent":pId,
					  "cate_name":$("#productNameInput").val(),
					  "order_num": $("#orderNumInput").val()
					}
					//调用ajax
					var ajaxUrl = "/PCIndustryChart/insert";
					//转圈提示
	    			common.showLoading();
					common.interfaceAjaxFunction(ajaxUrl,param,_this.insertSucess);
              
				
			}else if(id.length== 0&&pId.length!=0){
				var fw_parent= pId;
           		if (fw_parent) {
               		var param = {
					  "fw_parent":fw_parent,
					  "cate_name":$("#productNameInput").val(),
					  "order_num": $("#orderNumInput").val()
					}
					//调用ajax
					var ajaxUrl = "/PCIndustryChart/insert";
					//转圈提示
	    			common.showLoading();
					common.interfaceAjaxFunction(ajaxUrl,param,_this.insertSucess);
               }else{
               	   layer.msg("请先选择父节点",1000);
               }
			}else if(id.length!= 0){
				// 修改 保存
				var param = { 
					 "pk_industry_chart":id,
					 "cate_name":$("#productNameInput").val(),
					 "order_num":parseInt($("#orderNumInput").val())
				}
				var ajaxUrl = "/PCIndustryChart/update";
				//转圈提示
    			common.showLoading();
				common.interfaceAjaxFunction(ajaxUrl,param,_this.updateSucess);
			}
			if (treenode.level == 3) {
		   	   if(treenode.productName == $("#kmProductInput").val()){
		   	   	return;
		   	   }
		       var str = window.sessionStorage.key_productId;
		       var productIds = new Array;
		       if(str){
		       	productIds = str.split(",");
		       }
			   	var param = {
			   		"pk_user":window.localStorage.userid,
			   		"pk_industry_chart":id,
			   		"pk_product_list":productIds
			   		}
					//调用ajax
				var ajaxUrl = "/pc/industryProduct/insert";
				//转圈提示
    			common.showLoading();
				common.interfaceAjaxFunction(ajaxUrl,param,keyIndustryMaintance.productInsertSucess);
		   }
          
        });
        $("#cancleButton").hide();
        $("#cancleButton").unbind().on("click", function () {
        	keyIndustryMaintance.showTreeNode(treenode);
            $("#cancleButton").hide();
        });
	},
	
	initialize:function(){
		//高度初始化
		keyIndustryMaintance.initPageHeight();
		keyIndustryMaintance.bindEvent();
		//加载第一个页面
		keyIndustryMaintance.initLeftTree();
		
	}
};
